package com.biconn.bigdata.es.repository;/**
 * Created by Administrator on 2018/8/4.
 */




import java.net.InetAddress;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.biconn.bigdata.es.client.config.ElasticsearchConfiger;

/**
 * Elasticsearch基类
 * botu
 * com.bicon.botu.es
 *
 * @author 123774135@qq.com
 * @create 2018-08-04 17:44
 **/
@Component
public class ElasticsearchClientRepository implements FactoryBean<TransportClient> ,InitializingBean,DisposableBean{

    private Logger logger = LoggerFactory.getLogger(ElasticsearchClientRepository.class);

    @Autowired
    private ElasticsearchConfiger elasticsearchConfiger;
    private TransportClient client;


    public TransportClient getClient() {
        return client;
    }

    public void setClient(TransportClient client) {
        this.client = client;
    }

    @Override
    public void destroy() throws Exception {
        client.close();
    }

    @Override
    public TransportClient getObject() throws Exception {
        return client;
    }

    @Override
    public Class<?> getObjectType() {
        return TransportClient.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        logger.info("开始进行初始化");
        Settings settings = Settings.builder().put("client.transport.sniff", true).put("node.name","node11").put("cluster.name",elasticsearchConfiger.getClusterName()).build();
        //elasticsearch 6.x
        client =  new PreBuiltTransportClient (settings).addTransportAddress(new TransportAddress(InetAddress.getByName(elasticsearchConfiger.getHost()),Integer.parseInt(elasticsearchConfiger.getPort())));
        //elasticsearch 5.x
        //client =  new PreBuiltTransportClient (settings).addTransportAddresses(new InetSocketTransportAddress(InetAddress.getByName(elasticsearchConfiger.getHost()),Integer.parseInt(elasticsearchConfiger.getPort())));
    }
}
